package com.ujinsung.utils.net
{
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.system.Security;
	import flash.system.SecurityDomain;
	
	/**
	 * 
	 * @author jinsung
	 * @email ujinsung@gmail.com
	 * @version 1.0 init.
	 */
	public class LoadUtil
	{	
		public function LoadUtil()
		{
		}
		
		/**
		 * @description load data file ex) xml and txt file 
		 * @param p_path
		 * @param p_successCB
		 * @param p_errorCB
		 * 
		 */
		public static function loadData( p_path:String, p_successCB:Function, p_errorCB:Function = null ) :URLLoader {
			var loader:URLLoader = new URLLoader();
			var request:URLRequest = new URLRequest( p_path );
			loader.addEventListener( Event.COMPLETE, p_successCB );
			loader.addEventListener( IOErrorEvent.IO_ERROR, p_errorCB != null ? p_errorCB : onErrorLoad );
			loader.load( request );
			return loader;
		}
		
		/**
		 * @description load image or movie ex) swf, jpg, png files
		 * @param p_path external file url
		 * @param p_successCB callback function when it sucess
		 * @param p_errorCB callback function when it fail
		 * 
		 */
		public static function loadExternal ( p_path:String, p_successCB:Function, p_errorCB:Function = null ):Loader
		{
			var loader:Loader
			
			loader = new Loader();
			
			var request:URLRequest = new URLRequest( p_path );
			
			loader.contentLoaderInfo.addEventListener( Event.INIT, p_successCB );
			
			loader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, p_errorCB != null ? p_errorCB : onErrorLoad );
			loader.contentLoaderInfo.addEventListener( IOErrorEvent.NETWORK_ERROR, p_errorCB != null ? p_errorCB : onErrorLoad );
			
			var context: LoaderContext = new LoaderContext( );
			context.checkPolicyFile = true;
			if( Security.sandboxType == Security.REMOTE )
			{
				context.securityDomain = SecurityDomain.currentDomain;
			}
			context.applicationDomain = ApplicationDomain.currentDomain;
			loader.load( request, context );
			return loader;
		}
		
		
		private static function onErrorLoad( p_errorEvent:IOErrorEvent ):void {
			//log ( p_errorEvent , this );
			throw ( p_errorEvent );
		}
	}
}